import React from 'react'
import { Toast } from 'antd-mobile'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { actions as newsActionCraetors } from '../../redux/modules/news'
import moment from 'moment';
import config from '../../../config';
import getQuery from '../../helpers/getQuery'
import './detail.less'

moment.locale('zh-cn');

const imgPath = 'http://file.winkse.com/Upload/Common/Salesman/qq'

class Detail extends React.PureComponent {

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }

  state = {
    AttachName: "5.",
    AttachUrl: "",
    Id: '',
    IsShowText: true,
    LastUpdateDate: "",
    Rank: 1,
    TerraceType: 4,
    TerraceTypeName: "",
    Text: "",
    Title: "",
    Type: 1,
    ViewCount: 0
  }

  componentWillMount() {
    const id = this.props.params.id

    this.fetchDetail(id)
    this.addView(id)
    /*this.fetchDisList({
      articleId: id,
      pageIndex: 1,
      pageSize: 20,
      userId: '' 
    })*/
  }

  componentDidMount() {
    const page = document.getElementById('forum-detail-page')
    const content = document.getElementById('inner-wrap')
    /*page.onscroll = () => {
      //为了保证兼容性，这里取两个值，哪个有值取哪一个
      //scrollTop就是触发滚轮事件时滚轮的高度
      var scrollTop = page.scrollTop || document.body.scrollTop;
      var pageH = page.clientHeight
      var contentH = content.clientHeight
      // 滚动到50公分左右作判断
      if (contentH - pageH > scrollTop + 50) {
        if (this.props.pageIndex < this.props.pageCount) {
          this.fetchDisList({
            articleId: id,
            pageIndex: this.props.pageIndex++,
            pageSize: 20,
            userId: '' 
          })
        } 
      }
    }*/
  }

  render() {
    return <section className="forum-detail-page" id="forum-detail-page">
      <div className="inner-wrap" id="inner-wrap">
        <div className="title">{this.state.Title}</div>
        <div className="sub">
          {moment(this.state.LastUpdateDate, 'YYYY-MM-DD HH:mm:ss').fromNow()} 
          <span>阅读 {this.state.ViewCount}</span>
          {this.state.Rank == 1 && <span className="tag top">顶</span>}
        </div>
        <div className="content" dangerouslySetInnerHTML={{ __html: this.state.Text }}></div>
        {/*<div className="discuss-list">
          {
            this.props.list.length > 0 ? [
              <div className="header" key="0">
                <span>精选留言</span>
                <a href="javascript:;" onClick={this.handleGo.bind(this)}>写留言</a>
              </div>,
              <div key="1">
                {
                  this.props.list.map((item,i) => <div className="item" key={i}>
                    <div className="avator"><img src={item.WxImgUrl}/></div>
                    <div className="content">
                      <div className="name">{item.CreateName}</div>
                      <div className="remark" dangerouslySetInnerHTML={{ __html: this.encodeContent(item.Comment) }}></div>
                    </div>
                    <div className="action" onClick={this.handleZan.bind(this, item.Id, i)}>
                      <i className="iconfont icon-praise_icon"></i> <span>{item.GoodCount}</span>
                    </div>
                  </div>
                  )
                }
              </div>
            ] : <a href="javascript:;" className="action" onClick={this.handleGo.bind(this)}>写留言</a>
          }
        </div>*/}
      </div>
    </section>
  }

  handleGo() {
    this.context.router.push(`${config.rootAlias}/forum/discuss/${this.state.Id}?userId=${getQuery('userId')}`)
  }

  handleZan(id, i) {
    this.props.actions.zanDis(id, i, json => {
      if (!json.IsSuccess) {
        Toast.info(json.Msg, 1)
      }
    })
  }

  fetchDetail(id) {
    this.props.actions.fetchDetail({id}, json => {
      if (json.IsSuccess) {
        this.setState({
          ...json.Data
        })
      } else {
        Toast.info(json.Msg, 1);
      }
    })
  }

  fetchDisList(params) {
    this.props.actions.fetchDisList(params, json => {
      if (!json.IsSuccess) {
        Toast.info(json.Msg, 1);
      }
    })
  } 

  addView(id) {
    this.props.actions.addView({id})
  }

  encodeContent(str) {
    const reg = /\[([^\]]+)\]/g;
    str = str.replace(reg, function(m, n) {
      if (n > 0 && n < 60) {
        return `<img src='${imgPath}/${n}.png' />`
      } else {
        return m
      }
    });
    return str
  }

}

const stateToProps = state => ({
  ...state.news
})

const dispatchToProps = dispatch => ({
  actions: bindActionCreators(newsActionCraetors, dispatch)
})

export default connect(stateToProps, dispatchToProps)(Detail);
